<?php

//http://phpjavascriptroom.com/?t=strm&p=youtubedataapi_v3_list#a_playlist_sample2
//https://code.google.com/p/google-api-php-client/source/browse/trunk/examples/youtube/my_uploads.php
//https://accounts.google.com/UpdateDomain
require_once 'Zend/Loader.php';

Zend_Loader::loadClass('Zend_Controller_Front');
require_once ("../library/UserAgentManager.class.php");
require_once ("../library/FeedUtil.class.php");
require_once ("../library/SecureManager.class.php");
$frontController = Zend_Controller_Front::getInstance();
$appConfig = $frontController->getParam('bootstrap')->getOptions();
$feedUtil = new FeedUtil();
$OAUTH2_CLIENT_ID = $appConfig['clientId'];
$OAUTH2_CLIENT_SECRET = $appConfig['clientSecret'];
$developerKey = $appConfig['developerKey'];

//print_r($appConfig);

$secureManager = new SecureManager();
setLogging('on');
session_start();
header('Access-control-allow-origin: *');   

if (isset($_POST['operation']))
{
    $operation = $_POST['operation'];
    switch ($operation)
    {
        case 'logout':
            logout();
            break;
        case 'auth_sub_token_upgrade':
            updateAuthSubToken($_GET['token']);
            break;
        case 'clear_session_var':
            clearSessionVar($_POST['name']);
            break;
        case 'retrieve_playlists':
            $feedUtil->retrievePlaylists($OAUTH2_CLIENT_ID, $OAUTH2_CLIENT_SECRET, $developerKey);
            break;
        case 'show_video':
            echoVideoPlayer($_GET['feed_url']);
            break;
        // top
        case 'feeds_from_playlist':
            if (isset($_POST['keyword']))
            {
                $playlistItems = $feedUtil->feedsFromKeyword($secureManager->sanitize($_POST['keyword']), $OAUTH2_CLIENT_ID, $OAUTH2_CLIENT_SECRET, $developerKey);
                $feedUtil->feedToHtml($playlistItems);
            }
            elseif (isset($_POST['feed_url']))
            {
                $playlistItems = $feedUtil->feeds_from_playlist($secureManager->sanitize($_POST['feed_url']), $OAUTH2_CLIENT_ID, $OAUTH2_CLIENT_SECRET, $developerKey);
                $feedUtil->feedToHtml($playlistItems);
            }

            break;
        case 'teaxtarea_from_palylist':
            teaxtarea_from_palylist($secureManager->sanitize($_POST['feed_url']), $developerKey);
            break;
        case 'teaxtarea_from_keyword':
            teaxtarea_from_keyword($secureManager->sanitize($_POST['keyword']), $developerKey);
            break;

        case 'feeds_from_keyword':
            $playlistItems = $feedUtil->feedsFromKeyword($secureManager->sanitize($_POST['keyword']), $OAUTH2_CLIENT_ID, $OAUTH2_CLIENT_SECRET, $developerKey);
            $html = $feedUtil->feedToHtml($playlistItems);
            echo $html;
            break;
        default:
            unsupportedOperation();
            break;
    }
}

/*
 * teaxtarea_from_palylist
 * @param String $feed_url
 */

function teaxtarea_from_palylist($feed_url, $developerKey)
{
    $_SESSION['feed_url'] = $feed_url;
    echo feedToTextArea($feed_url, $developerKey);
}

function teaxtarea_from_keyword($keyword, $developerKey)
{
    $_SESSION['keyword'] = $keyword;
    echo keywordToTextArea($keyword, $developerKey);
}

/*
 * feedToTextArea
 * @param String $feed_url 
 */

function feedToTextArea($feed_url, $developerKey)
{
    if (empty($feed_url))
    {
        $feed_url = "";
        $share_url = 'http://' . $_SERVER['SERVER_NAME'];
    }
    else
    {
        $share_url = 'http://' . $_SERVER['SERVER_NAME'] . '?feed_url=' . urlencode($feed_url);
    }
    $secureManager = new SecureManager();
    $share_this_playlist="";
    $share_this_playlist.="<div id='googleplus'>";
    $share_this_playlist.="<script type='text/javascript'>";
    $share_this_playlist.="(function() {";
    $share_this_playlist.="   var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;";
    $share_this_playlist.="  po.src = 'https://apis.google.com/js/plusone.js'; ";
    $share_this_playlist.="  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); ";
    $share_this_playlist.="  })();";
    $share_this_playlist.=" </script>";
    $share_this_playlist.=" <g:plus action='share' href=" . $share_url . "></g:plus>";
    $share_this_playlist.="</div>";
    $share_this_playlist.="<div id='share_url'>";
    $share_this_playlist.="<p>this URL:</p>";
    $share_this_playlist.="<input type='text' id='share_url_shorten' size='20' maxlength='20' value=" . "'" . $secureManager->get_tiny_url($share_url, $developerKey) . "'" . " /></p>";
    $share_this_playlist.="<input type='hidden'" . " name='feed_share_url' value=" . "'";
    $share_this_playlist.= $share_url;
    $share_this_playlist.="'" . " /></div>";

    return $share_this_playlist;
}



function keywordToTextArea($keyword, $developerKey)
{
    if (empty($keyword))
    {
        $share_url = 'http://' . $_SERVER['SERVER_NAME'];
    }
    else
    {
        $share_url = 'http://' . $_SERVER['SERVER_NAME'] . '?keyword=' . urlencode($keyword);
    }
    $secureManager = new SecureManager();
    $share_this_playlist="";
    $share_this_playlist.="<div id='googleplus'>";
    $share_this_playlist.="<script type='text/javascript'>";
    $share_this_playlist.="(function() {";
    $share_this_playlist.="   var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;";
    $share_this_playlist.="  po.src = 'https://apis.google.com/js/plusone.js'; ";
    $share_this_playlist.="  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); ";
    $share_this_playlist.="  })();";
    $share_this_playlist.=" </script>";
    $share_this_playlist.=" <g:plus action='share' href=" . $share_url . "></g:plus>";
    $share_this_playlist.="</div>";
    $share_this_playlist.="<div id='share_url'>";
    $share_this_playlist.="<p>this URL:</p>";
    $share_this_playlist.="<input type='text' id='share_url_shorten' size='20' maxlength='20' value=" . "'" . $secureManager->get_tiny_url($share_url, $developerKey) . "'" . " /></p>";
    $share_this_playlist.="<input type='hidden'" . " name='feed_share_url' value=" . "'";
    $share_this_playlist.= $share_url;
    $share_this_playlist.="'" . " /></div>";
    return $share_this_playlist;
}

/**
 * Log a message to the session variable array.
 *
 * @param string $message The message to log.
 * @param string $messageType The type of message to log.
 * @return void
 */
function logMessage($message, $messageType)
{
    if (!isset($_SESSION['log_maxLogEntries']))
    {
        $_SESSION['log_maxLogEntries'] = 20;
    }

    if (!isset($_SESSION['log_currentCounter']))
    {
        $_SESSION['log_currentCounter'] = 0;
    }

    $currentCounter = $_SESSION['log_currentCounter'];
    $currentCounter++;

    if ($currentCounter > $_SESSION['log_maxLogEntries'])
    {
        $_SESSION['log_currentCounter'] = 0;
    }

    $logLocation = 'log_entry_' . $currentCounter . '_' . $messageType;
    $_SESSION[$logLocation] = $message;
    $_SESSION['log_currentCounter'] = $currentCounter;
}

/**
 * Enables logging.
 *
 * @param string $loggingOption 'on' to turn logging on, 'off' to turn logging off.
 * @param integer|null $maxLogItems Maximum items to log, default is 10.
 * @return void
 */
function setLogging($loggingOption, $maxLogItems = 10)
{
    switch ($loggingOption)
    {
        case 'on' :
            $_SESSION['logging'] = 'on';
            $_SESSION['log_currentCounter'] = 0;
            $_SESSION['log_maxLogEntries'] = $maxLogItems;
            break;
        case 'off':
            $_SESSION['logging'] = 'off';
            break;
    }
}

/**
 * Check whether logging is enabled.
 *
 * @return boolean Return true if session variable for logging is set to 'on'.
 */
function loggingEnabled()
{
    if ($_SESSION['logging'] == 'on')
    {
        return true;
    }
}

function logout()
{
    header('Location: ' . "/Index/ouath?logout");
    return;
}

/**
 * Helper function if an unsupported operation is passed into this files main loop.
 * @param array $post (Optional) The post variables that accompanied the operation, if available.
 * @return void
 */
function unsupportedOperation()
{
    $message = 'ERROR An unsupported operation has been called - post variables received ';

    if (loggingEnabled())
    {
        logMessage($message, 'error');
    }
    print $message;
}
